'use server'
import { auth } from "@/auth";
import { prisma } from "@/prisma";
import type { Topic } from "@prisma/client";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import z from "zod";
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

interface CreateTopicFormState {
  errors: {
    title?: string[];
    description?: string[];
    // 1.添加新的返回值可选
    _form?: string[];
  };
}


const schema = z.object({
  title: z.string().min(3, {
    message: "长度必须大于3"
  }).max(20, {
    message: "长度必须小于20"
  }).regex(/^[0-9a-zA-Z_]+$/i, {
    message: "长度必须大于3，小于20，只能包含字母、数字和下划线"
  }),
  description: z.string().min(3, {
    message: "长度必须大于3"
  }).max(1000, {
    message: "长度必须小于1000"
  })
})

/**
 * 创建话题
 * @param formData 
 */
export const createTopic = async (prevState: CreateTopicFormState, formData: FormData): Promise<CreateTopicFormState> => {
  await sleep(2000)
  // 2.制定返回值
  const title = formData.get("title");
  const description = formData.get("description");
  const result = schema.safeParse({
    title,
    description
  })
  // console.log('result',result);
  if (!result.success) {
    return {
      errors: result.error.flatten().fieldErrors,
    }
  }
  // 判断有没有登录
  const session = await auth()
  if (!session?.user) {
    return {
      errors: {
        _form: ["请先登录"],
      }
    }
  }
  console.log('session', session.user.id);
  let topic: Topic
  try {
    topic = await prisma.topic.create({
      data: {
        name: result.data.title,
        description: result.data.description,
        userId: session.user.id,
      }
    })
    // return {
    //   errors: {},
    // }
  } catch (error) {
    if (error instanceof Error) {
      return {
        errors: {
          _form: [error.message],
        }
      }
    } else {
      return {
        errors: {
          _form: ["创建失败"],
        }
      }
    }
  }
  revalidatePath('/');
  redirect(`/topics/${topic.name}`)
}
